import SparkMD5 from 'spark-md5'; // 引入 spark-md5 库

/**
 * 计算md5
 * @param file 文件
 * @returns md5
 */
export const fileMD5 = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();

        reader.onload = (event) => {
            const arrayBuffer = event.target.result;
            const md5 = new SparkMD5.ArrayBuffer();
            md5.append(arrayBuffer);
            const result = md5.end();

            resolve(result); // This is an ArrayBuffer, not a string
        };

        reader.onerror = (error) => {
            reject(error);
        };

        reader.readAsArrayBuffer(file);
    })
};

export const MD5 = async (file, onProgress) => {
    try {
        const arrayBuffer = await readFileAsArrayBuffer(file, onProgress);
        return calculateMD5(arrayBuffer);
    } catch (error) {
        console.error("Error calculating MD5:", error);
        throw error;
    }
};

const readFileAsArrayBuffer = (file, onProgress) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();

        reader.onprogress = (event) => {
            if (event.lengthComputable) {
                const progress = (event.loaded / event.total) * 100;
                onProgress(progress);
            }
        };

        reader.onload = (event) => {
            resolve(event.target.result);
        };

        reader.onerror = (error) => {
            reject(error);
        };

        reader.readAsArrayBuffer(file);
    });
};

const calculateMD5 = (arrayBuffer) => {
    const md5 = new SparkMD5.ArrayBuffer();
    md5.append(arrayBuffer);
    return md5.end();
};

export const shardMD5 = async (file) => {
    try {
        const arrayBuffer = await shardReadFileAsArrayBuffer(file);
        return shardCalculateMD5(arrayBuffer);
    } catch (error) {
        console.error("Error calculating MD5:", error);
        throw error;
    }
};

const shardReadFileAsArrayBuffer = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();

        reader.onload = (event) => {
            resolve(event.target.result);
        };

        reader.onerror = (error) => {
            reject(error);
        };

        reader.readAsArrayBuffer(file);
    });
};

const shardCalculateMD5 = (arrayBuffer) => {
    const md5 = new SparkMD5.ArrayBuffer();
    md5.append(arrayBuffer);
    return md5.end();
};

